import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Switch, message, Tabs } from 'antd';
import { useNavigate, useParams } from 'react-router-dom';
import { PageHeader } from '@/components/PageHeader';
import { MarkdownEditor } from '@/components/MarkdownEditor';
import { ArticlePreview } from '@/components/ArticlePreview';
import { useArticle } from '@/hooks/useArticle';
import { articleApi } from '@/api';
import type { Article, CreateArticleDto } from '@/types/article';
import { TagManager } from '@/components/TagManager';
import { useTranslation } from 'react-i18next';

export const ArticleEdit: React.FC = () => {
    const { t } = useTranslation();
    const [form] = Form.useForm();
    const navigate = useNavigate();
    const { id } = useParams();
    const [loading, setLoading] = useState(false);
    const { createArticle, updateArticle } = useArticle();
    const [activeTab, setActiveTab] = useState('edit');

    const fetchArticle = async () => {
        try {
            const { data } = await articleApi.detail(id!);
            form.setFieldsValue(data);
        } catch (error) {
            message.error(t('article.action.fetchError'));
            navigate('/');
        }
    };

    useEffect(() => {
        if (id) {
            fetchArticle();
        }
    }, [id]);

    const onFinish = async (values: CreateArticleDto) => {
        setLoading(true);
        try {
            if (id) {
                await updateArticle(id, values);
                message.success(t('article.action.updateSuccess'));
            } else {
                await createArticle(values);
                message.success(t('article.action.createSuccess'));
            }
            navigate('/');
        } catch (error) {
            message.error(id ? t('article.action.updateError') : t('article.action.createError'));
        } finally {
            setLoading(false);
        }
    };

    const [previewData, setPreviewData] = useState<Article>({
        id: id || '',
        title: '',
        content: '',
        slug: '',
        published: false,
        tags: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
    });

    // 监听表单值变化
    useEffect(() => {
        const formValues = form.getFieldsValue();
        setPreviewData(prev => ({
            ...prev,
            ...formValues,
        }));
    }, [activeTab]);

    // 监听表单值变化的另一种方式
    const handleFormValuesChange = () => {
        if (activeTab === 'preview') {
            const formValues = form.getFieldsValue();
            setPreviewData(prev => ({
                ...prev,
                ...formValues,
            }));
        }
    };

    // 移除 useEffect，改用 onTabChange 处理
    const handleTabChange = (key: string) => {
        setActiveTab(key);
        if (key === 'preview') {
            const formValues = form.getFieldsValue();
            setPreviewData(prev => ({
                ...prev,
                ...formValues,
            }));
        }
    };

    return (
        <div>
            <PageHeader
                title={id ? t('article.edit') : t('article.create')}
                showBack
            />
            <Tabs
                activeKey={activeTab}
                onChange={handleTabChange}
                items={[
                    {
                        key: 'edit',
                        label: t('article.form.edit'),
                        children: (
                            <Form
                                form={form}
                                layout="vertical"
                                onFinish={onFinish}
                                initialValues={{ published: false, tags: [] }}
                                onValuesChange={handleFormValuesChange}
                            >
                                <Form.Item
                                    name="title"
                                    label={t('article.form.title')}
                                    rules={[{ required: true, message: t('article.form.titleRequired') }]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="slug"
                                    label={t('article.form.slug')}
                                    rules={[{ required: true, message: t('article.form.slugRequired') }]}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="category"
                                    label={t('article.form.category')}
                                >
                                    <Input />
                                </Form.Item>

                                <Form.Item
                                    name="content"
                                    label={t('article.form.content')}
                                    rules={[{ required: true, message: t('article.form.contentRequired') }]}
                                >
                                    <MarkdownEditor />
                                </Form.Item>

                                <Form.Item
                                    name="published"
                                    label={t('article.form.status')}
                                    valuePropName="checked"
                                >
                                    <Switch />
                                </Form.Item>

                                <Form.Item
                                    name="tags"
                                    label={t('article.form.tags')}
                                >
                                    <TagManager />
                                </Form.Item>

                                <Form.Item>
                                    <Button type="primary" htmlType="submit" loading={loading}>
                                        {id ? t('article.action.update') : t('article.action.create')}
                                    </Button>
                                    <Button onClick={() => navigate('/')} style={{ marginLeft: 8 }}>
                                        {t('article.action.cancel')}
                                    </Button>
                                </Form.Item>
                            </Form>
                        ),
                    },
                    {
                        key: 'preview',
                        label: t('article.form.preview'),
                        children: <ArticlePreview article={previewData} />,
                    },
                ]}
            />
        </div>
    );
};

export default ArticleEdit;